<?php
namespace Common\Controller;
use Common\Controller\AppframeController;

require COMMON_PATH.'Controller/ApiTrait.php';
use Common\Controller\ApiTrait;

class ApibaseController extends AppbaseController {

    protected $_userType,$_user,$_userId; 
	
    use ApiTrait;

	public function __construct() {
		parent::__construct();
	}
	
	function _initialize() {
		parent::_initialize();

        $this->_userType=$this->getUserType();
        $this->getUserId($this->_userType);
	}

    /**
     * 获取用户分类，是商户还是普通用户
     * @param int $userType 用户分类，未登录用户为0，普通用户为1，商户为2
     * @DateTime 2017-07-12T11:17:00+0800
     * @return   int   用户分类
     */
    public function getUserType()
    {
        return I('userType/d',0);
    }

    public function getUserId($type)
    {
        switch ($type) {
            case 1:
                $this->_user=$this->_getMember();
                $this->_userId=$this->_user['id'];
                break;

            case 2:
                $this->_user=$this->_getBussiness();
                $this->_userId=$this->_user['id'];
                break;
            
            default:
                $this->_userId=0;
                $this->_user=[];
                break;
        }
    }

    public function checkLogin()
    {   
        if ($this->_userId==0) {
            $this->ajaxReturn(2,[],'请先登陆');
        }elseif($this->_userType==2 && $this->_user['is_checked']==0){
            $this->ajaxReturn(6,[],'资质审核中,还不能进行此项操作');
        }else{
            return true;
        }
    }

    public function _getMember()
    {
        $token=I('token/s');
        $user=M('User')->where(['token'=>$token,'token_expire_time'=>['GT',time()]])->find();
        if(empty($user)){
            return false;
        }else{
            return $user;
        }
    }

    public function _getBussiness()
    {
        $token=I('token/s');
        $user=M('Business')->where(['token'=>$token,'token_expire_time'=>['GT',time()]])->find();
        if(empty($user)){
            return false;
        }else{
            return $user;
        }
    }

    /**
     * 计算距离sql语句
     * @param $lat
     * @param $long
     * @return string
     */
    public function getDistanceSql($lat,$long){
        return "round(6378.138*2*asin(sqrt(pow(sin(
($lat*pi()/180-t.`lat`*pi()/180)/2),2)+cos($lat*pi()/180)*cos(t.`lat`*pi()/180)*
pow(sin( ($long*pi()/180-t.`lng`*pi()/180)/2),2)))*1000)";
    }
	
}